package com.foohoo.benchmark.jvm;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;

/**
 * 测试即时编译器编译优化(代码消除)对性能的提升
 * Benchmark                                         Mode  Cnt    Score     Error  Units
 * JustInTimeWithDeadCode.withDeadCode               avgt    3    0.476 ±   2.279  ns/op
 * JustInTimeWithDeadCode.withDeadCodeButExcludeJit  avgt    3  557.080 ± 215.266  ns/op
 * JustInTimeWithDeadCode.withoutDeadCode            avgt    3   26.951 ±  14.136  ns/op
 * 一句话结论: 被判定为热点代码后，即时编译器(jit)会通过多种手段对代码进行优化，可以显著提升性能(示例中分别为代码消除、普通优化和不优化)
 *
 * @author mzdbxqh
 * @date 2020-10-19 19:21
 **/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 3, time = 1)
@Fork(1)
@Threads(1)
@State(Scope.Benchmark)
public class JustInTimeWithDeadCode {

	@Benchmark
	public void withoutDeadCode(Blackhole bh) {
		Double a, b, c, d;
		a = Math.pow(Math.PI, Math.PI);
		b = Math.pow(Math.PI, Math.PI);
		c = Math.pow(Math.PI, Math.PI);
		d = Math.pow(Math.PI, Math.PI);
		bh.consume(a);
		bh.consume(b);
		bh.consume(c);
		bh.consume(d);
	}

	@CompilerControl(CompilerControl.Mode.EXCLUDE)
	@Benchmark
	public void withDeadCodeButExcludeJit() {
		Double a, b, c, d;
		a = Math.pow(Math.PI, Math.PI);
		b = Math.pow(Math.PI, Math.PI);
		c = Math.pow(Math.PI, Math.PI);
		d = Math.pow(Math.PI, Math.PI);
	}

	@Benchmark
	public void withDeadCode() {
		Double a, b, c, d;
		a = Math.pow(Math.PI, Math.PI);
		b = Math.pow(Math.PI, Math.PI);
		c = Math.pow(Math.PI, Math.PI);
		d = Math.pow(Math.PI, Math.PI);
	}

}
